﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BE;
using BLL;

namespace UI
{
    public partial class MusicPage : System.Web.UI.Page
    {
        List<Album> albums = null;

        protected void Page_Load(object sender, EventArgs e)
        {
                albums = AlbumManager.getAllAlbums();
                createMusicTable();
        }

        private void createMusicTable()
        {
            createTableHeader();

            foreach(Album album in albums)
            {
                TableRow row = new TableRow();
                tblMusic.Controls.Add(row);

                int id = album.Id;

                Image image = new Image();
                image.ImageUrl = "albumcovers/" + album.Image;
                image.CssClass = "ListCdCover";

                LinkButton linkInfo = new LinkButton();
                linkInfo.Text = album.Artist + " - " + album.Title;
                linkInfo.PostBackUrl = "AlbumPage.aspx?id=" + id;

                Label lblPrice = new Label();
                lblPrice.Text = album.Price.ToString();

                LinkButton linkAdd = new LinkButton();
                linkAdd.Text = "Add";
                linkAdd.CommandArgument = id.ToString();
                linkAdd.Command += CommandHandler;

                row.Controls.Add(createCell(image));
                row.Controls.Add(createCell(linkInfo));
                row.Controls.Add(createCell(lblPrice));
                row.Controls.Add(createCell(linkAdd));
            } 
        }

        private void createTableHeader()
        {
            TableRow row = new TableRow();
            tblMusic.Controls.Add(row);

            row.Controls.Add(createHeaderCell( "Cover"));
            row.Controls.Add(createHeaderCell("Title"));
            row.Controls.Add(createHeaderCell("Price"));
            row.Controls.Add(createHeaderCell("Add to cart"));
        }

        private TableCell createHeaderCell(string text)
        {
            TableCell cell = new TableCell();
            Label lbl = new Label();
            lbl.Text = text;
            cell.Controls.Add(lbl);
            cell.CssClass = text;
            return cell;
        }
        
        private TableCell createCell(Control ctl)
        {
            TableCell cell = new TableCell();
            cell.Controls.Add(ctl);
            cell.CssClass = "musicCell";
            return cell;
        }

        protected void CommandHandler(object sender, CommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument);
            ShoppingCart.Instance.addItem(AlbumManager.getAlbum(id));
            Master.UpdateCart();
        }
    }
}